package com.wjm.client.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.wjm.entity.Classroom;
import com.wjm.util.CacheUtil;
import com.wjm.util.StringUtil;

@Controller
@RequestMapping("/client/classroom")
public class ClassroomClientController {

	private final String listKey = "list";
	private final String pagesKey = "pages";
	private final String pageKey = "page";
	private final String statusKey = "status";
	private final String buKey = "buId";
	private final String buNameKey = "buName";
	private final String busKey = "bus";

	@RequestMapping("/query")
	public String query(int page, int buId, int status, Model model) {
		String result = "";
		try {
			// 如果该教学楼没有被禁用
			if (buId == 0 || (CacheUtil.getBuildings().get(buId) != null && CacheUtil.getBuildings().get(buId).getBuStatus() == 1) ) {
				List<Classroom> rooms = null;
				if (status == 1) {
					rooms = CacheUtil.getUseroom().get(buId);
					//System.out.println("CacheUtil.getUseroom():*********"+CacheUtil.getUseroom()+"==="+CacheUtil.getUseroom().get(buId));
				} else {
					rooms = CacheUtil.getUnuseroom().get(buId);
					//System.out.println("rooms:*********"+rooms+CacheUtil.getUseroom()+"==="+CacheUtil.getUseroom().get(buId));
				}
				List<Classroom> list = new ArrayList<>();
				int pages = 1;
				if (rooms != null) {
					int total = rooms.size();
					int number = Integer.parseInt(CacheUtil.getProperties().getProperty(StringUtil.CLASSROOM_NUM));
					pages = total % number == 0 ? (total / number) : (total / number + 1);
					// 计算需要取到哪
					int end = (page * number) > total ? total : (page * number);
					// 将数据放入list中
					for (int i = (page - 1) * number; i < end; i++) {
						list.add(rooms.get(i));
						//System.out.println("===rooms.get(i).getCrNo()=="+rooms.get(i).getCrNo());
					}
				}
				model.addAttribute(listKey, list);
				model.addAttribute(pageKey, page);
				model.addAttribute(pagesKey, pages);
				model.addAttribute(statusKey, status);
				model.addAttribute(buKey, buId);
				if (buId == 0) {
					model.addAttribute(buNameKey, "选择教学楼");
				} else {
					model.addAttribute(buNameKey, CacheUtil.getBuildings().get(buId).getBuName());
				}
				model.addAttribute(busKey, CacheUtil.getBuildings());
				result = "/client/rec/desk-rec";
			} else {
				result = "fail";
				model.addAttribute("msg", "该教学楼已被禁用！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result = "error";
		}

		return result;
	}

}
